﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class AlignedObj : MonoBehaviour
{
    public AlignedTarget target;
    public float minDis;
    public string operationName;
    public UnityEvent onAlignedAction;
    [HideInInspector]
    public bool activeAlign = false;
    public event Action onAligned;
    protected bool canAligned = false;
    protected bool grabbed = false;
    private void Awake()
    {
    }
    // Use this for initialization
    void Start () {
	}
	
	// Update is called once per frame
	void Update () {
        if (activeAlign && grabbed)
        {
            CalculationDistance();
        }
	}

    public void ActiveAligned()
    {
        activeAlign = true;
    }

    public void Aligned()
    {
        if (canAligned)
        {
            transform.parent = target.transform.parent;
            transform.localPosition = target.transform.localPosition;
            transform.localRotation = target.transform.localRotation;
            target.Hide();
            onAlignedAction.Invoke();
            if (onAligned != null)
            {
                onAligned();
            }
        }
    }

    void OnGrabbed()
    {

    }

    void OnUngrabbed()
    {
        if (canAligned)
        {
            Aligned();
        }
    }

    void CalculationDistance()
    {
        if (Vector3.Distance(target.transform.position, transform.position) < minDis)
        {
            canAligned = true;
        }
        else
        {
            canAligned = false;
        }
    }
}
